// PackageGatewayService.java
package com.example.gymlearning.service;

import com.example.gymlearning.entity.PackageGatewaySession;
import com.example.gymlearning.entity.QuizQuestion;
import com.example.gymlearning.entity.UserPackageProgress;
import com.example.gymlearning.mapper.PackageGatewayMapper;
import com.example.gymlearning.mapper.QuizQuestionMapper;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.util.*;
import java.util.stream.Collectors;

@Slf4j
@Service
@RequiredArgsConstructor
public class PackageGatewayService {

    private final PackageGatewayMapper packageGatewayMapper;
    private final QuizQuestionMapper quizQuestionMapper;
    private final UserProgressService userProgressService;
    private final KnowledgePackageService knowledgePackageService;

    /**
     * 创建知识包闯关会话
     */
    public Long createPackageGatewaySession(Long userId, Long packageId) {
        try {
            // 检查是否解锁
            if (!userProgressService.isPackageGatewayUnlocked(userId, packageId)) {
                throw new RuntimeException("知识包闯关尚未解锁");
            }

            // 获取题目
            List<QuizQuestion> questions = generatePackageGatewayQuestions(packageId);
            if (questions.isEmpty()) {
                throw new RuntimeException("该知识包暂无题目");
            }

            // 创建会话
            PackageGatewaySession session = new PackageGatewaySession();
            session.setUserId(userId);
            session.setPackageId(packageId);
            session.setStatus("IN_PROGRESS");
            session.setStartTime(new Date());
            session.setTotalQuestions(questions.size());
            session.setCorrectAnswers(0);
            session.setScore(0);

            // 存储题目ID
            String questionIds = questions.stream()
                    .map(q -> q.getId().toString())
                    .collect(Collectors.joining(","));
            session.setQuestionIds(questionIds);

            packageGatewayMapper.insertSession(session);
            log.info("创建知识包闯关会话: userId={}, packageId={}, 题目数量={}", userId, packageId, questions.size());

            return session.getId();
        } catch (Exception e) {
            log.error("创建知识包闯关会话失败: {}", e.getMessage(), e);
            throw new RuntimeException("创建闯关会话失败: " + e.getMessage());
        }
    }

    /**
     * 生成知识包闯关题目
     */
    private List<QuizQuestion> generatePackageGatewayQuestions(Long packageId) {
        // 从知识包内所有知识点中随机抽取题目
        List<QuizQuestion> allQuestions = quizQuestionMapper.findByPackageId(packageId);

        // 过滤正式题目
        List<QuizQuestion> formalQuestions = allQuestions.stream()
                .filter(q -> "FORMAL".equals(q.getUsageType()))
                .collect(Collectors.toList());

        // 如果题目数量足够，随机选择15道题
        int targetCount = 15;
        if (formalQuestions.size() <= targetCount) {
            return formalQuestions;
        }

        // 随机选择题目
        Collections.shuffle(formalQuestions);
        return formalQuestions.subList(0, targetCount);
    }

    /**
     * 获取知识包闯关题目
     */
    public List<QuizQuestion> getPackageGatewayQuestions(Long sessionId) {
        PackageGatewaySession session = packageGatewayMapper.findSessionById(sessionId);
        if (session == null) {
            throw new RuntimeException("会话不存在");
        }

        String[] questionIds = session.getQuestionIds().split(",");
        List<Long> ids = Arrays.stream(questionIds)
                .map(Long::valueOf)
                .collect(Collectors.toList());

        return quizQuestionMapper.findByIds(ids);
    }

    /**
     * 完成知识包闯关
     */
    public boolean completePackageGateway(Long sessionId, Integer score, Integer correctAnswers, Integer totalQuestions) {
        try {
            PackageGatewaySession session = packageGatewayMapper.findSessionById(sessionId);
            if (session == null) {
                throw new RuntimeException("会话不存在");
            }

            // 更新会话
            session.setStatus("COMPLETED");
            session.setScore(score);
            session.setCorrectAnswers(correctAnswers);
            session.setEndTime(new Date());

            // 计算用时（分钟）
            long durationMs = session.getEndTime().getTime() - session.getStartTime().getTime();
            session.setDuration((int) (durationMs / (1000 * 60)));

            packageGatewayMapper.updateSession(session);

            // 判断是否通过（80%正确率）
            boolean isPassed = (correctAnswers * 100 / totalQuestions) >= 80;

            if (isPassed) {
                // 更新用户进度
                userProgressService.completePackageGateway(
                        session.getUserId(),
                        session.getPackageId(),
                        score,
                        correctAnswers,
                        totalQuestions
                );
            } else {
                // 闯关失败，可以重试
                session.setStatus("FAILED");
                packageGatewayMapper.updateSession(session);
            }

            log.info("完成知识包闯关: sessionId={}, 得分={}/{}, 通过={}",
                    sessionId, score, totalQuestions, isPassed);

            return isPassed;
        } catch (Exception e) {
            log.error("完成知识包闯关失败: {}", e.getMessage(), e);
            throw new RuntimeException("完成闯关失败: " + e.getMessage());
        }
    }

    /**
     * 获取知识包闯关结果统计
     */
    public Map<String, Object> getPackageGatewayStats(Long packageId) {
        Map<String, Object> stats = new HashMap<>();

        // 题目总数
        int totalQuestions = quizQuestionMapper.countByPackageId(packageId);
        stats.put("totalQuestions", totalQuestions);

        // 预计题目数量
        stats.put("expectedQuestions", Math.min(15, totalQuestions));

        // 预计时间（基于题目数量）
        stats.put("estimatedDuration", Math.min(15, totalQuestions) * 2); // 每道题2分钟

        // 通过率要求
        stats.put("passingRate", 80);

        return stats;
    }
}